package com.supeng.PMdepot.net;

import android.app.Activity;
import android.content.Context;

import com.duowan.mobile.netroid.DefaultRetryPolicy;
import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.Request;
import com.duowan.mobile.netroid.RequestQueue;
import com.supeng.PMdepot.MApplication;
import com.supeng.PMdepot.R;
import com.supeng.PMdepot.common.Config;
import com.supeng.PMdepot.common.Constant;
import com.supeng.PMdepot.entity.ServiceResult;
import com.supeng.PMdepot.util.Utils;
import com.supeng.PMdepot.widget.dialog.CProgressDialog;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import static com.supeng.PMdepot.common.Constant.maxRequestCount;
import static com.supeng.PMdepot.common.Constant.maxRequestTimer;


/***
 * 网络请求框架
 * 最新请求机制
 * 加入缓存
 */
public class NetUtils {
    private static RequestQueue mQueue = Netroid.newRequestQueue(MApplication.getContext());

    public static RequestQueue getmQueue() {
        return mQueue;
    }

    public static void setmQueue(RequestQueue mQueue) {
        NetUtils.mQueue = mQueue;
    }

    public static void get(final Activity context, String method, final String msg, final NetCallBack<ServiceResult> callBack, final Type rspCls) {
        if (!Constant.isCache) {
            if (!Utils.isConnected(context)) {
                if (callBack != null)
                    callBack.failed(context.getResources().getString(R.string.callBackFailed));
                return;
            }
        }

        CProgressDialog progressDialog = null;
        if (msg != null) {
            progressDialog = new CProgressDialog(context, R.style.CustomDialog);
            progressDialog.setMessage(msg);
            progressDialog.setOwnerActivity(context);//处理activity关闭奔溃问题
            progressDialog.setCancelable(true);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {

            }
        }

        String url = method;
        final CProgressDialog finalProgressDialog = progressDialog;
        SpSRequest request = new SpSRequest(Request.Method.GET, url,
                new Listener<ServiceResult>() {

                    @Override
                    public void onSuccess(ServiceResult response) {
                        if (msg != null){
                            if ( finalProgressDialog != null && finalProgressDialog.isShowing()) { //处理activity关闭奔溃问题
                                Activity activity = finalProgressDialog.getOwnerActivity();
                                if ( activity != null && !activity.isFinishing()){
                                    finalProgressDialog.dismiss();
                                }
                            }
                        }
                        if (callBack != null) {
                            if (response != null) {
                                callBack.success(response);

                            } else {
                                callBack.failed(context.getResources().getString(R.string.parseFailed));
                            }
                        }
                    }

                    @Override
                    public void onError(NetroidError error) {
                        if (msg != null)
                            finalProgressDialog.dismiss();
                        if (callBack != null)
                            callBack.failed(context.getResources().getString(R.string.callBackFailed));
                    }

                    @Override
                    public void onUsedCache() {
                        super.onUsedCache();
                        if (msg != null)
                            finalProgressDialog.dismiss();
                        if (callBack != null)
                            callBack.onUsedCache(context.getResources().getString(R.string.callBackFailed));
                    }
                }, rspCls);
        isSaveCache(context, request);
        if(Config.isUserLogin()) {
            request.addHeader("Authorization", Config.getUserInfo().getToken());
        }
        request.setRetryPolicy(new DefaultRetryPolicy(maxRequestTimer, maxRequestCount, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        request.setTag(context);
        mQueue.add(request);
    }

    public static void post(final Activity context, String method, final JSONObject jsonObject, final String msg, final NetCallBack<ServiceResult> callBack, final Type rspCls) {

        if (!Constant.isCache) {
            if (!Utils.isConnected(context)) {
                if (callBack != null) {
                    callBack.failed(context.getResources().getString(R.string.callBackFailed));
                }
                return;
            }
        }
        CProgressDialog progressDialog = null;
        if (msg != null) {
            progressDialog = new CProgressDialog(context, R.style.CustomDialog);
            progressDialog.setOwnerActivity(context);//处理activity关闭奔溃问题
            progressDialog.setMessage(msg);
            progressDialog.setCancelable(true);
            try {
                if (!progressDialog.isShowing()) {
                    progressDialog.show();
                }
            } catch (Exception e) {

            }
        }
        String url = method;
        final CProgressDialog finalProgressDialog = progressDialog;
        SpRequest request = new SpRequest(Request.Method.POST, url, jsonObject, new Listener<ServiceResult>() {
            @Override
            public void onSuccess(ServiceResult response) {
                if (msg != null){
                    if ( finalProgressDialog != null && finalProgressDialog.isShowing()) { //处理activity关闭奔溃问题
                        Activity activity = finalProgressDialog.getOwnerActivity();
                        if ( activity != null && !activity.isFinishing()){
                            finalProgressDialog.dismiss();
                        }
                    }
                }
                if (callBack != null) {
                    if (response != null) {
                        callBack.success(response);
                    } else {
                        callBack.failed(context.getResources().getString(R.string.parseFailed));
                    }
                }
            }

            @Override
            public void onError(NetroidError error) {
                if (msg != null)
                    finalProgressDialog.dismiss();
                if (callBack != null)
                    callBack.failed(context.getResources().getString(R.string.callBackFailed));

            }

            @Override
            public void onUsedCache() {
                super.onUsedCache();
                if (msg != null)
                    finalProgressDialog.dismiss();
                if (callBack != null)
                    callBack.onUsedCache(context.getResources().getString(R.string.callBackFailed));
            }
        }, rspCls);
        isSaveCache(context, request);
        if(Config.isUserLogin()) {
            request.addHeader("Authorization", Config.getUserInfo().getToken());
        }
        request.setRetryPolicy(new DefaultRetryPolicy(maxRequestTimer, maxRequestCount, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));//
        request.setTag(context);
        mQueue.add(request);
    }

    //json缓存机制
    public static void isSaveCache(Context context, Request request) {
        if (Constant.isCache) {
            if (Utils.isConnected(context)) {
                request.setForceUpdate(true);
            }
            //缓存天数
            request.setCacheExpireTime(TimeUnit.DAYS, 10);
        }
    }
    public interface NetCallBack<T> {
        public void success(T rspData);

        public void failed(String msg);

        public void onUsedCache(String msg);
    }
}
